<template>
  <div
    id="screen"
    :style="{
      width: `${designWidth}px`,
      height: `${designHeight}px`,
      transform: style.transform,
      visibility: isReady ? 'visible' : 'hidden',
    }"
    :class="{ 'screen-loading': !isReady }"
  >
    <!-- 加载提示 -->
    <div v-if="!isReady" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p>大屏加载中...</p>
    </div>

    <!-- 主要内容 -->
    <div class="screen-content" v-show="isReady">
      <div class="box">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
        <div>6</div>
      </div>
    </div>

    <!-- 分辨率提示（开发环境） -->
    <div v-if="showDebugInfo" class="debug-info">
      <p>设计尺寸: {{ designWidth }} × {{ designHeight }}</p>
      <p>当前窗口: {{ currentWidth }} × {{ currentHeight }}</p>
      <p>缩放比例: {{ scaleRatio.toFixed(3) }}</p>
      <p>适配模式: {{ adaptMode }}</p>
    </div>
  </div>
</template>

<script>
import { debounce } from "@/utils/test2.js";

export default {
  name: "LargeScreen",
  props: {
    // 设计稿宽度
    designWidth: {
      type: Number,
      default: 1920,
    },
    // 设计稿高度
    designHeight: {
      type: Number,
      default: 1080,
    },
    // 适配模式：scale(等比缩放) | fit(适应容器) | full(铺满容器)
    mode: {
      type: String,
      default: "scale",
      validator: (value) => ["scale", "fit", "full"].includes(value),
    },
    // 是否显示调试信息
    debug: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      style: {
        transform: "scale(1) translate(-50%, -50%)",
      },
      currentWidth: 0,
      currentHeight: 0,
      scaleRatio: 1,
      adaptMode: "scale",
      isReady: false,
      showDebugInfo: false,
    };
  },
  computed: {
    // 计算缩放比例
    scaleInfo() {
      if (!this.currentWidth || !this.currentHeight) {
        return { scaleX: 1, scaleY: 1, ratio: 1, mode: "scale" };
      }

      const scaleX = this.currentWidth / this.designWidth;
      const scaleY = this.currentHeight / this.designHeight;

      let finalScaleX, finalScaleY, mode;

      switch (this.mode) {
        case "fit":
          // 等比缩放，保证完全显示
          const minScale = Math.min(scaleX, scaleY);
          finalScaleX = finalScaleY = minScale;
          mode = "fit";
          break;
        case "full":
          // 填满屏幕，可能会裁剪
          const maxScale = Math.max(scaleX, scaleY);
          finalScaleX = finalScaleY = maxScale;
          mode = "full";
          break;
        case "scale":
        default:
          // 自由缩放
          finalScaleX = scaleX;
          finalScaleY = scaleY;
          mode = "scale";
          break;
      }

      return {
        scaleX: finalScaleX,
        scaleY: finalScaleY,
        ratio: Math.min(finalScaleX, finalScaleY),
        mode,
      };
    },
  },
  watch: {
    mode: {
      handler() {
        this.updateScale();
      },
      immediate: false,
    },
  },
  methods: {
    // 获取当前窗口尺寸
    getCurrentSize() {
      try {
        return {
          width: window.innerWidth || document.documentElement.clientWidth,
          height: window.innerHeight || document.documentElement.clientHeight,
        };
      } catch (error) {
        console.warn("获取窗口尺寸失败:", error);
        return { width: 1920, height: 1080 };
      }
    },

    // 更新缩放
    updateScale() {
      try {
        const size = this.getCurrentSize();
        this.currentWidth = size.width;
        this.currentHeight = size.height;

        const { scaleX, scaleY, ratio, mode } = this.scaleInfo;
        this.scaleRatio = ratio;
        this.adaptMode = mode;

        // 生成transform样式
        this.style.transform = `scale(${scaleX}, ${scaleY}) translate(-50%, -50%)`;

        // 触发自定义事件
        this.$emit("scale-change", {
          scaleX,
          scaleY,
          ratio,
          mode,
          width: this.currentWidth,
          height: this.currentHeight,
        });

        // 首次加载完成
        if (!this.isReady) {
          this.$nextTick(() => {
            this.isReady = true;
            this.$emit("ready");
          });
        }
      } catch (error) {
        console.error("更新缩放失败:", error);
      }
    },

    // 防抖后的缩放函数
    debouncedUpdateScale: null,

    // 初始化
    init() {
      try {
        // 创建防抖函数
        this.debouncedUpdateScale = debounce(this.updateScale, 100);

        // 初始化显示
        this.updateScale();

        // 监听窗口变化
        window.addEventListener("resize", this.debouncedUpdateScale);
        window.addEventListener("orientationchange", this.debouncedUpdateScale);

        // 开发环境显示调试信息
        if (this.debug || process.env.NODE_ENV === "development") {
          this.showDebugInfo = true;
        }

        console.log("大屏适配初始化完成");
      } catch (error) {
        console.error("大屏适配初始化失败:", error);
      }
    },

    // 销毁
    destroy() {
      try {
        window.removeEventListener("resize", this.debouncedUpdateScale);
        window.removeEventListener("orientationchange", this.debouncedUpdateScale);
        console.log("大屏适配已销毁");
      } catch (error) {
        console.error("销毁大屏适配失败:", error);
      }
    },

    // 手动刷新
    refresh() {
      this.updateScale();
    },

    // 切换适配模式
    switchMode(mode) {
      if (["scale", "fit", "full"].includes(mode)) {
        this.$emit("update:mode", mode);
      }
    },
  },

  mounted() {
    this.init();
  },

  beforeDestroy() {
    this.destroy();
  },
};
</script>

<style lang="less" scoped>
#screen {
  position: fixed;
  left: 50%;
  top: 50%;
  transform-origin: 0 0;
  transition: transform 0.3s ease;
  z-index: 100;

  &.screen-loading {
    visibility: hidden;
  }
}

.screen-content {
  width: 100%;
  height: 100%;
}

.loading-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  color: #fff;
  z-index: 1000;

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid rgba(255, 255, 255, 0.3);
    border-top: 3px solid #fff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  p {
    margin: 0;
    font-size: 16px;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.debug-info {
  position: fixed;
  top: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-family: monospace;
  z-index: 9999;

  p {
    margin: 2px 0;
  }
}

.box {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: aqua;
  padding: 10px;
  box-sizing: border-box;

  div {
    background-color: blanchedalmond;
    border: 1px solid #000;
    flex: 1;
  }
}

// 响应式优化
@media screen and (max-width: 768px) {
  .debug-info {
    font-size: 10px;
    padding: 6px 8px;
  }
}

// 高分辨率屏幕优化
@media screen and (min-resolution: 2dppx) {
  .box {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }
}
</style>
